package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.PatrolAreaUser;
import com.ruoyi.system.domain.bo.PatrolAreaUserBo;
import com.ruoyi.system.domain.vo.PatrolAreaUserVo;
import com.ruoyi.system.mapper.PatrolAreaUserMapper;
import com.ruoyi.system.service.IPatrolAreaUserService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 巡区用户分配Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-01
 */
@RequiredArgsConstructor
@Service
public class PatrolAreaUserServiceImpl implements IPatrolAreaUserService {

    private final PatrolAreaUserMapper baseMapper;

    private final ISysUserService  userService;
    /**
     * 查询巡区用户分配
     */
    @Override
    public PatrolAreaUserVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询巡区用户分配列表
     */
    @Override
    public TableDataInfo<PatrolAreaUserVo> queryPageList(PatrolAreaUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PatrolAreaUser> lqw = buildQueryWrapper(bo);
        Page<PatrolAreaUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询巡区用户分配列表
     */
    @Override
    public List<PatrolAreaUserVo> queryList(PatrolAreaUserBo bo) {
        LambdaQueryWrapper<PatrolAreaUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据巡区ID查询用户分配列表
     */
    @Override
    public List<PatrolAreaUserVo> queryByAreaId(Long areaId) {
        LambdaQueryWrapper<PatrolAreaUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(PatrolAreaUser::getAreaId, areaId);
        lqw.eq(PatrolAreaUser::getStatus, "0");
        List<PatrolAreaUserVo> patrolAreaUserVos = baseMapper.selectVoList(lqw);
        List<PatrolAreaUserVo> collect = patrolAreaUserVos.stream().map(k ->
        {
            Long userId = k.getUserId();
            SysUser sysUser = userService.selectUserById(userId);
            k.setUserName(sysUser.getUserName());
            return k;
        }).collect(Collectors.toList());


        return  collect;
    }

    /**
     * 根据用户ID查询巡区分配列表
     */
    @Override
    public List<PatrolAreaUserVo> queryByUserId(Long userId) {
        LambdaQueryWrapper<PatrolAreaUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(PatrolAreaUser::getUserId, userId);
        lqw.eq(PatrolAreaUser::getStatus, "0");
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PatrolAreaUser> buildQueryWrapper(PatrolAreaUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PatrolAreaUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAreaId() != null, PatrolAreaUser::getAreaId, bo.getAreaId());
        lqw.eq(bo.getUserId() != null, PatrolAreaUser::getUserId, bo.getUserId());
        lqw.eq(bo.getAssignType() != null, PatrolAreaUser::getAssignType, bo.getAssignType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PatrolAreaUser::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增巡区用户分配
     */
    @Override
    public Boolean insertByBo(PatrolAreaUserBo bo) {
        PatrolAreaUser add = BeanUtil.toBean(bo, PatrolAreaUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改巡区用户分配
     */
    @Override
    public Boolean updateByBo(PatrolAreaUserBo bo) {
        PatrolAreaUser update = BeanUtil.toBean(bo, PatrolAreaUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PatrolAreaUser entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除巡区用户分配
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量分配用户到巡区
     */
    @Override
    public Boolean batchAssignUsers(Long areaId, List<Long> userIds, List<String> userNames, Integer assignType) {
        if (userIds == null || userIds.isEmpty()) {
            return false;
        }

        // 先删除该巡区的所有分配
        LambdaQueryWrapper<PatrolAreaUser> deleteWrapper = Wrappers.lambdaQuery();
        deleteWrapper.eq(PatrolAreaUser::getAreaId, areaId);
        baseMapper.delete(deleteWrapper);

        // 批量插入新的分配
        for (int i = 0; i < userIds.size(); i++) {
            PatrolAreaUser areaUser = new PatrolAreaUser();
            areaUser.setAreaId(areaId);
            areaUser.setUserId(userIds.get(i));
            areaUser.setAssignType(assignType);
            areaUser.setStatus("0");

            // 设置备注信息，包含用户姓名
            String remark = "";
            if (userNames != null && i < userNames.size()) {
                remark = "分配用户：" + userNames.get(i);
            }
            areaUser.setRemark(remark);

            baseMapper.insert(areaUser);
        }

        return true;
    }

    /**
     * 取消用户巡区分配
     */
    @Override
    public Boolean cancelUserAssign(Long areaId, Long userId) {
        LambdaQueryWrapper<PatrolAreaUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PatrolAreaUser::getAreaId, areaId);
        wrapper.eq(PatrolAreaUser::getUserId, userId);
        return baseMapper.delete(wrapper) > 0;
    }
}
